/*
 * Copyright (c) 2015. For Intelligent Group.
 */
package com.intelligent.ispc.client.core.view.analysis.grr;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.intelligent.ispc.client.core.controller.GrrController;
import com.intelligent.ispc.client.core.modal.SearchCsvTableModel;
import com.intelligent.ispc.client.core.modal.grr.ChoiceItemDto;
import com.intelligent.ispc.client.core.modal.grr.ConfigModel;
import com.intelligent.ispc.client.core.modal.grr.GroupModel;
import com.intelligent.ispc.client.core.view.AbstractPanel;
import com.intelligent.ispc.client.core.view.analysis.grr.render.FileTableCellRenderer;
import com.intelligent.ispc.client.event.ExportBtnEnabledEvent;
import com.intelligent.ispc.client.event.StatusBarMsgChangeEvent;
import com.intelligent.ispc.client.ex.JTextFieldEx;
import com.intelligent.ispc.client.utils.*;
import com.intelligent.ispc.client.utils.ExceptionMessages;
import com.intelligent.ispc.client.utils.FileUtils;
import com.intelligent.ispc.common.utils.*;
import com.intelligent.ispc.constant.AppConstant;
import com.intelligent.ispc.core.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;

/**
 * Created by cherry on 16/9/7.
 */
@Component
public class GrrMainPanel extends AbstractPanel {

    @Autowired
    private GrrController grrController;
    @Autowired
    private ChoiceItemDialog choiceItemDialog;
    @Autowired
    private ExportChoiceItemDialog exportChoiceItemDialog;

    private GroupModel<String> groupModel;
    private SearchCsvTableModel fileModel;
    private ConfigModel configModel;

    @Override
    public void initDataSource() {

        resetContentPanel();

        GrrConfigDto configDto = grrController.findGrrConfig();
        configModel.setData(configDto);
        analysisPanel.setConfigModel(configModel);
        viewDataPanel.setConfigModel(configModel);

        if (!AppConstant.GRR_MODEL_SLOT.equals(configModel.getSchema())) {
            slotPanel.removeAll();
            slotPanel.setBorder(BorderFactory.createEmptyBorder());
        }

        partTf.setText(configModel.getPartCount() + "");
        operatorTf.setText(configModel.getAppraiserCount() + "");
        trialTf.setText(configModel.getTrialCount() + "");
        excellentLbl.setText("0% < Excellent < " + configModel.getRules()[0] + "%");
        adequateLbl.setText(configModel.getRules()[0] + "% <= Adequate < " + configModel.getRules()[1] + "%");
        marginalLbl.setText(configModel.getRules()[1] + "% <= Marginal < " + configModel.getRules()[2] + "%");
        badLbl.setText(configModel.getRules()[2] + "% <= Bad < " + "100%");

        fileModel.setGrrData(grrController.findFiles());
        FileDataDto fileDataDto = getCurrentSelectedFile();
        if (fileDataDto != null) {
            setSelectedDataCache(fileDataDto);
            if (AppConstant.GRR_MODEL_SLOT.equals(configModel.getSchema())) {
                fillDataToSlotStrategy(fileDataDto);
            }
        }
        ApplicationBeanUtils.getBean(AnalysisPanel.class).initDataSource();
        ApplicationBeanUtils.getBean(ViewDataPanel.class).initDataSource();
    }

    @Override
    public void initView() {
        partTf.setEnabled(false);
        operatorTf.setEnabled(false);
        trialTf.setEnabled(false);
        excellentLbl.setForeground(Colur.GREEN);
        adequateLbl.setForeground(Colur.BLUE);
        marginalLbl.setForeground(Colur.ORANGE);
        badLbl.setForeground(Colur.RED);
        fileTable.getTableHeader().setVisible(false);
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setPreferredSize(new Dimension(0, 0));
        fileTable.getTableHeader().setDefaultRenderer(renderer);

        //set columns width;
        fileTable.getColumnModel().getColumn(0).setPreferredWidth(10);
        fileTable.getColumnModel().getColumn(0).setMaxWidth(50);
        fileTable.getColumnModel().getColumn(0).setMinWidth(30);
        fileTable.getColumnModel().getColumn(1).setPreferredWidth(100);
        fileTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
        analysisPanel.initView();
        viewDataPanel.initView();
    }

    @Override
    @PostConstruct
    public void initComponents() {
        JPanel searchPanel = new JPanel(new GridBagLayout());
        JPanel rightPanel = new JPanel(new GridBagLayout());
        JPanel topBtnPanel = new JPanel(new GridBagLayout());
        searchPanel.setBorder(BorderFactory.createEmptyBorder());
        rightPanel.setBorder(BorderFactory.createEmptyBorder());
        topBtnPanel.setBorder(BorderFactory.createEmptyBorder());

        JPanel filePanel = new JPanel(new GridBagLayout());
        JPanel modulePanel = new JPanel(new GridBagLayout());
        JPanel rulePanel = new JPanel(new GridBagLayout());
        JPanel groupPanel = new JPanel(new GridBagLayout());
        slotPanel = new JPanel(new GridBagLayout());
        slotPanel.setBorder(BorderFactory.createEmptyBorder());

        /* left panel init components start */
        filePanel.setBorder(BorderFactory.createTitledBorder("CSV"));
        modulePanel.setBorder(BorderFactory.createTitledBorder("Model"));
        rulePanel.setBorder(BorderFactory.createTitledBorder("Rule"));
        groupPanel.setBorder(BorderFactory.createTitledBorder("Group"));
        JScrollPane fileScrollPanel = new JScrollPane();
        fileScrollPanel.setBorder(BorderFactory.createEmptyBorder());

        String[] columns = new String[]{"", "name"};
        fileTable = new JTable();
        fileModel = new SearchCsvTableModel(columns);
        fileSorter = new TableRowSorter(fileModel);

        fileTable.setModel(fileModel);
        fileTable.setRowSorter(fileSorter);

        TableColumn column = fileTable.getColumnModel().getColumn(0);
        column.setCellRenderer(new FileTableCellRenderer(fileTable));

        configModel = new ConfigModel();
        analysisBtn = new JButton("Analysis");
        importFileBtn = new JButton("Import");
        deleteFileBtn = new JButton("Delete");
        emptyFileBtn = new JButton("Empty All");
        reloadFileBtn = new JButton("Reload");
        slotStrategyBtn = new JButton("OK");

        fileFilterTf = new JTextFieldEx();
        partTf = new JTextField();
        operatorTf = new JTextField();
        trialTf = new JTextField();
        excellentLbl = new JLabel();
        adequateLbl = new JLabel();
        marginalLbl = new JLabel();
        badLbl = new JLabel();

        groupBox = new JComboBox();
        groupModel = new GroupModel();
        groupBox.setModel(groupModel);
        final Dimension groupComboBoxSize = new Dimension(50, 25);
        groupBox.setPreferredSize(groupComboBoxSize);
        groupPanel.add(groupBox, new GBC(0, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(10, 0, 10, 5));
        fileScrollPanel.setViewportView(fileTable);
        fileFilterTf.setPlaceHolder("Filter");

        slotStrategyField = new JTextArea();
        slotStrategyField.setLineWrap(true);
        slotStrategyField.setWrapStyleWord(true);
        final Dimension fileScrollPaneSize = new Dimension(150, 200);
        fileScrollPanel.setPreferredSize(fileScrollPaneSize);

        filePanel.add(fileScrollPanel, new GBC(0, 0, 2, 1).setFill(GBC.BOTH).setWeight(100, 100));
        filePanel.add(fileFilterTf, new GBC(0, 1, 2, 1).setFill(GBC.BOTH).setWeight(100, 0));
        filePanel.add(analysisBtn, new GBC(0, 2, 2, 1).setFill(GBC.BOTH).setWeight(100, 0));
        filePanel.add(importFileBtn, new GBC(0, 3).setFill(GBC.BOTH).setWeight(50, 0));
        filePanel.add(deleteFileBtn, new GBC(1, 3).setFill(GBC.BOTH).setWeight(50, 0));
        filePanel.add(emptyFileBtn, new GBC(0, 4).setFill(GBC.BOTH).setWeight(50, 0));
        filePanel.add(reloadFileBtn, new GBC(1, 4).setFill(GBC.BOTH).setWeight(50, 0));
        filePanel.add(slotPanel, new GBC(0, 5).setFill(GBC.BOTH).setWeight(100, 0));

        modulePanel.add(new JLabel("Part"), new GBC(0, 0).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(5, 0, 0, 2));
        modulePanel.add(partTf, new GBC(1, 0).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(5, 0, 0, 5));
        modulePanel.add(new JLabel("Operator"), new GBC(0, 1).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(5, 0, 0, 2));
        modulePanel.add(operatorTf, new GBC(1, 1).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(5, 0, 0, 5));
        modulePanel.add(new JLabel("Trial"), new GBC(0, 2).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(5, 0, 0, 2));
        modulePanel.add(trialTf, new GBC(1, 2).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(5, 0, 5, 5));

        rulePanel.add(excellentLbl, new GBC(0, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(5, 0, 2, 0));
        rulePanel.add(adequateLbl, new GBC(0, 1).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(5, 0, 2, 0));
        rulePanel.add(marginalLbl, new GBC(0, 2).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(5, 0, 2, 0));
        rulePanel.add(badLbl, new GBC(0, 3).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(5, 0, 2, 0));

        searchPanel.add(filePanel, new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 15));
        searchPanel.add(slotPanel, new GBC(0, 1).setFill(GBC.BOTH).setWeight(100, 20));
        searchPanel.add(groupPanel, new GBC(0, 2).setFill(GBC.BOTH).setWeight(100, 20));
        searchPanel.add(modulePanel, new GBC(0, 3).setFill(GBC.BOTH));
        searchPanel.add(rulePanel, new GBC(0, 4).setFill(GBC.BOTH));
        searchPanel.add(new JPanel(), new GBC(0, 5).setFill(GBC.BOTH).setWeight(100, 100));
        /* left panel init components end */

        choiceItemBtn = new JButton("Choice Test Item");

        exportMenu = new JPopupMenu();
        resultMenu = new JMenuItem("Only Result");
        dataMenu = new JMenuItem("Result and Data");

        exportMenu.setBorderPainted(true);
        exportMenu.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        exportMenu.add(resultMenu);
        exportMenu.addSeparator();
        exportMenu.add(dataMenu);

        tabbedPane = new JTabbedPane();
        tabbedPane.addTab("GRR", analysisPanel);
        tabbedPane.addTab("View Data", viewDataPanel);

        JLabel titleLabel = new JLabel("Analysis/GRR");
        titleLabel.setFont(FontFactory.createPageTileFont());

        topBtnPanel.add(titleLabel, new GBC(0, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(0, 0, 0, 0));
        topBtnPanel.add(choiceItemBtn, new GBC(1, 0).setFill(GBC.HORIZONTAL).setInsets(0, 0, 0, 5));

        rightPanel.add(topBtnPanel, new GBC(0, 0).setFill(GBC.BOTH));
        rightPanel.add(tabbedPane, new GBC(0, 1).setFill(GBC.BOTH).setWeight(100, 100));

        JScrollPane leftScrollPanel = new JScrollPane();
        leftScrollPanel.setBorder(BorderFactory.createEmptyBorder());
        final Dimension leftScrollPane = new Dimension(200, 400);
        leftScrollPanel.setPreferredSize(leftScrollPane);
        leftScrollPanel.setViewportView(searchPanel);

        rightScrollPanel = new JScrollPane();
        rightScrollPanel.setBorder(BorderFactory.createEmptyBorder());
        rightPanel.setBorder(BorderFactory.createEmptyBorder());
        final Dimension rightScrollPane = new Dimension(700, 400);
        rightScrollPanel.setPreferredSize(rightScrollPane);
        rightScrollPanel.setViewportView(rightPanel);

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false, leftScrollPanel, rightPanel);
        splitPane.setBorder(BorderFactory.createEmptyBorder());
        splitPane.setDividerSize(UIConstant.SPLIT_DIVIDE_SIZE);
        this.setLayout(new GridBagLayout());
        this.add(splitPane, new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100));

        initComponentsEvent();
    }

    /**
     * set data source for groupModel
     *
     * @param grrGroupDto current choice group
     */
    public void loadGroup(GrrGroupDto grrGroupDto) {
        groupModel.setData(grrGroupDto);
        FileDataDto selectedData = getCacheSelectedFile();
        String fileName = selectedData.getName();
        List<ChoiceItemDto> dtos = grrController.findItems(fileName);
        choiceItemDialog.setTableData(dtos);
        exportChoiceItemDialog.setTableData(dtos);

        if (AppConstant.GRR_MODEL_SLOT.equals(configModel.getSchema())) {
            fillDataToSlotStrategy(selectedData);
        }
        componentsToggleShow(true);
    }

    /**
     * show Export Menu
     *
     * @param invoker component is showing
     */
    public void showExportMenu(java.awt.Component invoker) {
        final int yCoordinate = 25;
        exportMenu.show(invoker, 0, yCoordinate);
    }

    private void initComponentsEvent() {
        analysisBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (e.getClickCount() == 1) {
                    resetContentPanel();
                    if (AppConstant.GRR_MODEL_SLOT.equals(configModel.getSchema())) {
                        slotStrategyBtnEvent();
                    } else {
                        FileDataDto fileDataDto = getCurrentSelectedFile();
                        if (fileDataDto != null) {
                            setSelectedDataCache(fileDataDto);
                            initContentPanel();
                        } else {
                            AppMessageFactory.showErrorDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GRR_NO_SELECT_FILE));
                        }
                    }
                }
            }
        });

        importFileBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                importBtnEvent();
            }
        });

        fileFilterTf.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                update(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                update(e);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                update(e);
            }

            private void update(DocumentEvent e) {
                String value = fileFilterTf.getText();
                if (value.length() == 0) {
                    fileSorter.setRowFilter(null);
                } else {
                    fileSorter.setRowFilter(RowFilter.regexFilter(value, 1));
                }

                fileTable.repaint();
            }
        });

        deleteFileBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteFileBtnEvent();
            }
        });

        emptyFileBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int optionFlag = AppMessageFactory.showConfirmDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GLOBAL_IS_EMPTY));
                if (optionFlag == 0) {
                    emptyFileBtnEvent();
                }
            }
        });

        reloadFileBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                reloadFileBtnEvent();
            }
        });

        groupBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    int selectedGroupIndex = groupBox.getSelectedIndex();
                    FileDataDto fileDataDto = getCacheSelectedFile();
                    groupModel.setSelectedGroup(selectedGroupIndex);

                    if (fileDataDto == null || selectedGroupIndex == -1) {
                        return;
                    }
                    String path = fileDataDto.getSavePath();
                    String name = fileDataDto.getName();

                    viewDataPanel.setFilePath(path);
                    viewDataPanel.setCurrentGroup(groupModel.getSelectedGroup());
                    analysisPanel.setFilePathAndName(path, name);
                    analysisPanel.setCurrentGroup(groupModel.getSelectedGroup());

                    GrrParamDto grrParamDto = new GrrParamDto();
                    grrParamDto.setFilePath(path);
                    viewDataPanel.loadTable();
                    analysisPanel.loadSummary();
                }
            }
        });

        fileTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                int row = ((JTable) e.getSource()).rowAtPoint(e.getPoint());
                int rowIndex = ((JTable) e.getSource()).convertRowIndexToModel(row);
                fileModel.setSelectOneCheck(rowIndex);
                FileDataDto fileDataDto = getCurrentSelectedFile();

                if (fileDataDto != null) {
                    FileDataDto cacheSelectedFile = getCacheSelectedFile();
                    String currentFileName = fileDataDto.getName();
                    String analysisFileName = "";
                    if (cacheSelectedFile != null) {
                        analysisFileName = cacheSelectedFile.getName();
                        if (currentFileName.equals(analysisFileName) && groupModel.getSelectedGroup() != null) {
                            componentsToggleShow(true);
                        } else {
                            componentsToggleShow(false);
                        }
                    } else {
                        componentsToggleShow(false);
                    }

                    if (AppConstant.GRR_MODEL_SLOT.equals(configModel.getSchema())) {
                        fillDataToSlotStrategy(fileDataDto);
                    }
                    grrController.updateFileData(fileDataDto);
                }
            }
        });

        slotStrategyBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                resetContentPanel();
                slotStrategyBtnEvent();
            }
        });

        choiceItemBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                choiceItemBtnEvent();
            }
        });

        resultMenu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String filePath = "";
                FileDataDto selectedData = getCacheSelectedFile();
                if (selectedData == null) {
                    AppMessageFactory.showErrorDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GRR_NO_SELECT_FILE));
                } else {
                    filePath = selectedData.getSavePath();
                }

                if (groupModel == null || groupModel.getSelectedGroup() == null) {
                    AppMessageFactory.showErrorDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GRR_NO_SELECT_GROUP));
                }

                String fileName = selectedData.getName();
                String type = "Summary";
                exportChoiceItemDialog.showDialog(fileName, filePath, groupModel.getSelectedGroup(), type);
            }
        });

        dataMenu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String filePath = "";
                FileDataDto selectedData = getCacheSelectedFile();
                if (selectedData == null) {
                    AppMessageFactory.showErrorDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GRR_NO_SELECT_FILE));
                } else {
                    filePath = selectedData.getSavePath();
                }

                if (groupModel == null || groupModel.getSelectedGroup() == null) {
                    AppMessageFactory.showErrorDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GRR_NO_SELECT_GROUP));
                }

                String fileName = selectedData.getName();
                String type = "Detail";
                exportChoiceItemDialog.showDialog(fileName, filePath, groupModel.getSelectedGroup(), type);
            }
        });

        exportChoiceItemDialog.getSubmitBtn().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                FileDataDto selectedData = getCacheSelectedFile();
                String filePath = selectedData.getSavePath();
                if (!exportChoiceItemDialog.checkItemCount()) {
                    AppMessageFactory.showErrorDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GRR_NO_SELECT_ITEM));
                } else {
                    exportChoiceItemDialog.setVisible(false);
                    if (("Detail").equals(exportChoiceItemDialog.getExportType())) {
                        grrController.exportSummaryAndDetail(filePath, groupModel.getSelectedGroup(), exportChoiceItemDialog.getItemNames());
                    } else {
                        grrController.exportSummary(filePath, groupModel.getSelectedGroup(), exportChoiceItemDialog.getItemNames());
                    }
                    exportChoiceItemDialog.setCacheData();
                    exportChoiceItemDialog.setVisible(false);
                    Thread.currentThread().interrupt();
                }
            }
        });
    }

    /**
     * analysis button response event
     */
    public void analysisBtnEvent() {
        FileDataDto selectedData = getCacheSelectedFile();
        if (selectedData != null) {
            try {
                grrController.findGroup(selectedData);
            } catch (UIException e) {
                EventBusUtils.post(new StatusBarMsgChangeEvent(e.getMessage(), "error"));
            }
        } else {
            AppMessageFactory.showErrorDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GRR_NO_SELECT_FILE));
        }
    }

    private void initContentPanel() {
        viewDataPanel.resetViewDataPanel();
        analysisBtnEvent();
    }

    private void importBtnEvent() {
        List<KeyValueDto> fileDtos = Lists.newArrayList();
        String regType = ".?(?:csv)";
        String[] selectedFiles = FileUtils.fileSelect(GrrMainPanel.this, fileDtos, regType);

        if (!StringUtils.isBlank(selectedFiles[0]) && fileDtos != null) {
            if (!fileDtos.isEmpty()) {
                List<String> existNames = grrController.validateFiles(fileDtos);

                StringBuffer alertMsg = new StringBuffer();

                if (existNames != null && !existNames.isEmpty()) {
                    for (int i = fileDtos.size() - 1; i >= 0; i--) {
                        if (existNames.contains(fileDtos.get(i).getKey())) {
                            alertMsg.append(fileDtos.get(i).getKey());
                            alertMsg.append(System.getProperty("line.separator"));
                            fileDtos.remove(i);
                        }
                    }
                }
                grrController.importFile(fileDtos, null);
                fileModel.setGrrData(grrController.findFiles());

                if (StringUtils.isNotBlank(selectedFiles[1])) {
                    alertMsg.append(selectedFiles[1]);
                }
                if (StringUtils.isNotBlank(alertMsg)) {
                    AppMessageFactory.showWarningDialog(ResourceBundleUtils.getString(com.intelligent.ispc.common.utils.ExceptionMessages.EXCEPTION_GLOBAL_FILE_ALREADY_EXISTED)
                            + System.getProperty("line.separator") + alertMsg.toString());
                }
            }
        }
    }

    private void deleteFileBtnEvent() {
        FileDataDto fileDataDto = getCurrentSelectedFile();
        if (fileDataDto != null) {
            int optionFlag = AppMessageFactory.showConfirmDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GLOBAL_IS_DELETE));
            if (optionFlag == 0) {
                grrController.deleteFile(fileDataDto);
                fileModel.setGrrData(grrController.findFiles());
                groupModel.removeAllElements();

                slotPanel.removeAll();
                slotPanel.setBorder(BorderFactory.createEmptyBorder());
                resetContentPanel();
            }
        } else {
            AppMessageFactory.showWarningDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GRR_NO_SELECT_FILE));
        }
    }

    private FileDataDto getCacheSelectedFile() {
        FileDataDto fileDataDto = null;
        List<FileDataDto> dtos = fileModel.getSelectedDataCache();
        if (dtos != null && !dtos.isEmpty()) {
            fileDataDto = dtos.get(0);
        }
        return fileDataDto;
    }

    private void setSelectedDataCache(FileDataDto fileDataDto) {
        List<FileDataDto> values = Lists.newArrayList();
        values.add(fileDataDto);
        fileModel.setSelectedDataCache(values);
    }

    private FileDataDto getCurrentSelectedFile() {
        FileDataDto fileDataDto = null;
        List<FileDataDto> dtos = fileModel.getSelectedFile();
        if (dtos != null && !dtos.isEmpty()) {
            fileDataDto = dtos.get(0);
        }
        return fileDataDto;
    }

    private void emptyFileBtnEvent() {
        groupModel.removeAllElements();
        grrController.deleteAllFiles();
        fileModel.setGrrData(grrController.findFiles());

        resetContentPanel();
        slotPanel.removeAll();
        slotPanel.setBorder(BorderFactory.createEmptyBorder());
    }

    private void reloadFileBtnEvent() {
        grrController.reloadFile();
        fileModel.setGrrData(grrController.findFiles());
        resetContentPanel();

        if (getCurrentSelectedFile() == null || AppConstant.GRR_MODEL_NORMAL.equals(configModel.getSchema())) {
            slotPanel.removeAll();
            slotPanel.setBorder(BorderFactory.createEmptyBorder());
        }
    }

    private void fillDataToSlotStrategy(FileDataDto fileDataDto) {
        if (fileDataDto != null) {
            GrrParamDto grrParamDto = new GrrParamDto();
            grrParamDto.setFilePath(fileDataDto.getSavePath());
            String fileName = fileDataDto.getName();

            GrrItemDto grrItemDto = grrController.findDimensionByFileName(fileName);
            slotPanel.removeAll();
            slotPanel.setBorder(BorderFactory.createEmptyBorder());
            slotPanel.setBorder(BorderFactory.createTitledBorder("Test strategy"));
            if (grrItemDto != null) {
                slotStrategyField.setText(grrItemDto.getDimension());
            }
            JScrollPane strategyPanel = new JScrollPane(slotStrategyField);
            strategyPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            final Dimension strategyPanelSize = new Dimension(100, 100);
            strategyPanel.setPreferredSize(strategyPanelSize);

            slotPanel.add(strategyPanel, new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100).setInsets(5, 0, 0, 0));
            slotPanel.add(slotStrategyBtn, new GBC(0, 1).setFill(GBC.HORIZONTAL).setWeight(100, 100).setInsets(5, 0, 0, 0));
        }
    }

    private void slotStrategyBtnEvent() {
        FileDataDto fileDataDto = getCurrentSelectedFile();
        String dimension = slotStrategyField.getText().trim();
        if (!checkStrategy(dimension)) {
            return;
        }

        if (fileDataDto != null) {
            setSelectedDataCache(fileDataDto);
            grrController.updateGrrItemByDimension(fileDataDto.getName(), dimension);
            initContentPanel();
        } else {
            AppMessageFactory.showWarningDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GRR_NO_SELECT_FILE));
        }
    }
    /* file event deal end */

    private boolean checkStrategy(String value) {
        boolean flag = true;
        if (StringUtils.isNotBlank(value)) {
            String[] groupData = value.split(";");
            for (int i = 0; i < groupData.length; i++) {
                if (!StringUtils.isBlank(groupData[i])) {
                    String[] data = groupData[i].split(",");
                    Set<String> dataSet = Sets.newHashSet();
                    for (int j = 0; j < data.length; j++) {
                        dataSet.add(data[j]);
                    }

                    if (data.length != configModel.getAppraiserCount()) {
                        flag = false;
                        AppMessageFactory.showErrorDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GRR_NOT_MATCH_STRATEGY_COUNT));
                        break;
                    }

                    if (dataSet.size() != configModel.getAppraiserCount()) {
                        flag = false;
                        AppMessageFactory.showErrorDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GRR_NOT_CONTAIN_COMMON_COLUMNS));
                        break;
                    }

                } else {
                    flag = false;
                }
            }
        }
        return flag;
    }

    private void choiceItemBtnEvent() {
        FileDataDto selectedData = getCacheSelectedFile();
        if (selectedData != null) {
            String fileName = selectedData.getName();
            String filePath = selectedData.getSavePath();
            choiceItemDialog.showDialog(fileName, filePath, groupModel.getSelectedGroup());
        }
    }

    private void resetContentPanel() {
        componentsToggleShow(false);
        JScrollBar jsVB = rightScrollPanel.getVerticalScrollBar();
        if (jsVB != null) {
            jsVB.setValue(0);
        }

        groupModel.removeAllElements();
        analysisPanel.resetAnalysisPanel();
        viewDataPanel.resetViewDataPanel();
    }

    private void componentsToggleShow(boolean isShow) {
        choiceItemBtn.setEnabled(isShow);
        EventBusUtils.post(new ExportBtnEnabledEvent(UIConstant.MODULE_GRR, isShow));
        viewDataPanel.getSubmitBtn().setEnabled(isShow);
        groupBox.setEnabled(isShow);
    }

    @Autowired
    private AnalysisPanel analysisPanel;
    @Autowired
    private ViewDataPanel viewDataPanel;

    private JPanel slotPanel;
    private JTable fileTable;
    private JTextFieldEx fileFilterTf;
    private TableRowSorter fileSorter;
    private JTextArea slotStrategyField;
    private JButton slotStrategyBtn;
    private JButton analysisBtn;
    private JButton importFileBtn;
    private JButton deleteFileBtn;
    private JButton emptyFileBtn;
    private JButton reloadFileBtn;
    private JTextField partTf;
    private JTextField operatorTf;
    private JTextField trialTf;
    private JLabel excellentLbl;
    private JLabel adequateLbl;
    private JLabel marginalLbl;
    private JLabel badLbl;
    private JComboBox groupBox;
    private JButton choiceItemBtn;
    private JPopupMenu exportMenu;
    private JMenuItem resultMenu;
    private JMenuItem dataMenu;
    private JTabbedPane tabbedPane;
    private JScrollPane rightScrollPanel;

}
